package com.deltabravomedia.theoldtoad.server;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
@SuppressWarnings("serial")
public class UploadImage extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse res)
  			throws ServletException, IOException {
		try {
			String fileName = req.getQueryString();  
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(req);
			FileItemStream imageItem = iter.next();
			InputStream imgStream = imageItem.openStream();
		
			// construct our entity objects
			Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream));
			Image myImage = new Image(fileName, imageBlob);
			
			// persist image
			PersistenceManager pm = PMF.get().getPersistenceManager();

	        String query = "select from " + Image.class.getName() + " where name == '" + fileName + "'";
	        List<Image> items = (List<Image>) pm.newQuery(query).execute();
	        if (items.isEmpty()) {
				pm.makePersistent(myImage);
	        } else {
	            for (Image item : items) {
	            	pm.deletePersistent(item);
	            }
				pm.makePersistent(myImage);
	        }

			pm.close();
			
			// respond to query
			res.setContentType("text/plain");
			res.getOutputStream().write("OK!".getBytes());  
			res.getOutputStream().write(fileName.getBytes());  
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}